//
//  HomeDetialViewController.m
//  YiKao2
//
//  Created by Mac Jc on 15/8/1.
//  Copyright (c) 2015年 Mac Jc. All rights reserved.
//

#import "HomeDetialViewController.h"
#import "AllHeader.h"
#import "HomeNavigationVIew.h"
#import "HomeDetialHeaderVIew.h"
#import "CommentTableViewCell.h"
#import "HomeDetialModel.h"
//  长按手势
#import "GHContextMenuView.h"
#import "HomeDeyialFooterView.h"
#import "HomeCommentModel.h"
#import "ShareViewController.h"

//获取图片详情
//#define kURL @"http://arts1.dlab.com.cn/app/photo"
#define kURL @"http://www.arts1.cn/app/photo"
//获取收藏状态
//#define kGetCollectStatus @"http://arts1.dlab.com.cn/app/getcollectstatus"
#define kGetCollectStatus @"http://www.arts1.cn/app/getcollectstatus"

//获取评论列表
//#define kGetComment @"http://arts1.dlab.com.cn/app/getcomments"
#define kGetComment @"http://www.arts1.cn/app/getcomments"

//发布评论
//#define kAddComment @"http://arts1.dlab.com.cn/app/addcomment"
#define kAddComment @"http://www.arts1.cn/app/addcomment"

//点赞
//#define kZan @"http://arts1.dlab.com.cn/app/zan"
#define kZan @"http://www.arts1.cn/app/zan"

//获取关注状态
//#define kSetFollow @"http://arts1.dlab.com.cn/app/getfollowstatus"
#define kSetFollow @"http://www.arts1.cn/app/getfollowstatus"


@interface HomeDetialViewController ()<UITableViewDelegate,UITableViewDataSource,GHContextOverlayViewDataSource, GHContextOverlayViewDelegate,UITextFieldDelegate>

// 滑动视图
@property (nonatomic ,retain) UITableView *tableView;

@property (nonatomic ,retain) HomeNavigationVIew *navigationView;

//@property (nonatomic ,retain) HomeDetialHeaderVIew *headerView;

@property (nonatomic ,strong) NSMutableArray *dataSource;

@property (nonatomic ,strong) NSMutableArray *commentArray;

//发表评论按钮
@property (nonatomic ,strong) HomeDeyialFooterView *footerView;
// 分享视图
@property (nonatomic, strong) ShareViewController *shareVC;

@property (nonatomic ,assign) int status;
@end

@implementation HomeDetialViewController

- (NSMutableArray *)dataSource{
    if (_dataSource == nil) {
        self.dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (NSMutableArray *)commentArray{
    if (_commentArray == nil) {
        self.commentArray = [NSMutableArray array];
    }
    return _commentArray;
}

- (void)viewDidLoad{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.hidden = YES;
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    [self createNaviagtionView];
    [self requestData];

    [self requestCollectstatus];
    [self requestGetComment];
    [self creactFooterView];
    [self requestGetfollowstatus];
    [self createTableView];
    [self createShareView];
    
}

- (void)loadView {
    [super loadView];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    
    [self.footerView setHidden:NO];
//    
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    //设置成NO表示当前控件响应后会传播到其他控件上，默认为YES。
    tapGestureRecognizer.cancelsTouchesInView = NO;
    //将触摸事件添加到当前view
    [self.view addGestureRecognizer:tapGestureRecognizer];
}

-(void)keyboardHide:(UITapGestureRecognizer*)tap{
    [self requestCommint];
    [self.view endEditing:YES];
}

- (void)keyboardWillChangeFrame:(NSNotification *)notification {
    
    CGRect keyboardEndFrame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSTimeInterval animationDuration = [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] integerValue];
    
    CGFloat height = keyboardEndFrame.size.height;
    CGFloat offset = _footerView.frame.origin.y;
    if (height > 0) {//第一次的时候height是0
        offset = height;
       CGRect frame = self.footerView.frame;
        frame.origin.y = SCREEN_HEIGHT - (offset + 50);
        _footerView.frame = frame;
        [self.view bringSubviewToFront:_footerView];
        [self.view setNeedsUpdateConstraints];
        [UIView animateWithDuration:animationDuration animations:^{
            [self.view layoutIfNeeded];
        }];
    }
}

- (void)keyboardWillHide:(NSNotification *)notification {
    
//    [self.footerView setHidden:YES];
    
    NSTimeInterval animationDuration = [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] integerValue];
    
//    self.doneBtnConstraintY.constant = 126.0;
    CGRect frame = self.footerView.frame;
    frame.origin.y = SCREEN_HEIGHT - 50;
    self.footerView.frame = frame;
    [self.view setNeedsUpdateConstraints];
    [UIView animateWithDuration:animationDuration animations:^{
        [self.view layoutIfNeeded];
    }];
}

/**
 *  判断该图片是否被收藏
 */
- (void)requestCollectstatus{
    
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"dataForKeyAndUid"];
    NSString *uid = dic[@"data"][@"uid"];
    NSString *key = dic[@"data"][@"key"];
    
    NSDictionary *pardic = nil;
    if (uid && key) {
        pardic = @{@"imgId":_imageID,
                   @"uid":uid,
                   @"key":key};
    }
    
    [manage POST:kGetCollectStatus parameters:pardic
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
             if (responseObject) {
                 NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
                 int status = [dic[@"status"] intValue];
                 dispatch_async(dispatch_get_main_queue(), ^{
                     _status = status;
//                     _headerView.status = status;
                     [self.tableView reloadData];
                 });
             }
             // 请求成功的时候调用这个block
             NSLog(@"数据请求--%@", dic);
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             // 请求失败的时候调用调用这个block
             NSLog(@"请求失败");
         }];
}

/**
 *  获取图片详情数据请求
 */
- (void)requestData{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSDictionary *pardic =  @{@"id":_imageID};
    
    [manage GET:kURL parameters:pardic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves) error:nil];
        int status = [dic[@"status"] intValue];
        
        if (responseObject)
        {
            if (status == 1)
            {
                
                HomeDetialModel *model = [[HomeDetialModel alloc] init];
                [model setValuesForKeysWithDictionary:dic[@"data"]];
                [self.dataSource addObject:model];
                dispatch_async(dispatch_get_main_queue(), ^{
//                    _headerView.model = model;
                    [self.tableView reloadData];
                });
            
                
                
            }
        }
        
//        NSLog(@"获取图片详情数据请求%@----------",dic);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}

/**
 *  获取关注的状态
 */
- (void)requestGetfollowstatus{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"dataForKeyAndUid"];
    NSString *uid = dic[@"data"][@"uid"];
    
    NSDictionary *pardic = nil;
    if (_userId && uid)
    {
        pardic = @{@"followuid":_userId,
                   @"uid":uid,
                   @"type":@"user"};
    }
    
    [manage GET:kSetFollow parameters:pardic
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
             if (responseObject) {
                 NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
                 int status = [dic[@"status"] intValue];
                 dispatch_async(dispatch_get_main_queue(), ^{
                     _navigationView.status = status;
                     _navigationView.userID = _userId;
                 });
             }
             // 请求成功的时候调用这个block
//             NSLog(@"数据请求--%@", dic);
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             // 请求失败的时候调用调用这个block
//             NSLog(@"请求失败");
         }];
}

/**
 *  获取评论列表
 */
- (void)requestGetComment{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSDictionary *pardic = nil;
    if (_imageID)
    {
        pardic = @{@"topId":_imageID,
                   @"type":@"photo"};
    }

    [manage POST:kGetComment parameters:pardic
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
             NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
             int status = [dic[@"status"] intValue];
             if (status == 1) {
                 [self.commentArray removeAllObjects];
                 NSArray *list = dic[@"list"];
                 for (NSDictionary *dict in list) {
                     HomeCommentModel *model = [[HomeCommentModel alloc] init];
                     [model setValuesForKeysWithDictionary:dict];
                     [self.commentArray addObject:model];
                 }
                 [_tableView reloadData];
             }
             // 请求成功的时候调用这个block
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             // 请求失败的时候调用调用这个block
             NSLog(@"请求失败");
         }];
}

/**
 *  创建评论列表
 */
- (void)createTableView{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 44,SCREEN_WIDTH,SCREEN_HEIGHT - 94)];
//    _tableView.showsVerticalScrollIndicator = NO;
//    _tableView.backgroundColor = kCustomColor(235, 235, 235, 1);
    _tableView.backgroundColor = [UIColor whiteColor];
    [_tableView setSeparatorStyle:(UITableViewCellSeparatorStyleNone)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    
   [self.view addSubview:_tableView];
}
/**
 *  创建发布评论按钮
 */
- (void)creactFooterView{
    _footerView = [[HomeDeyialFooterView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 50, SCREEN_WIDTH, 50)];
    _footerView.backgroundColor = [UIColor whiteColor];
    _footerView.txtFiled.delegate = self;
    [_footerView.btnCommint addTarget:self action:@selector(Commint:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:_footerView];
}

//发布评论
- (void)Commint:(UIButton *)commint{
    //发布评论
    
//    [self requestCommint];
//    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
}

/**
 *  发布评论请求数据
 */
- (void)requestCommint{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"dataForKeyAndUid"];
    NSString *uid = dic[@"data"][@"uid"];
    NSString *key = dic[@"data"][@"key"];
    NSDictionary *pardic = nil;
    if (uid && key && _imageID && _footerView.txtFiled.text) {
        pardic = @{@"topId":_imageID,
                   @"uid":uid,
                   @"key":key,
                   @"type":@"photo",
                   @"Comment":_footerView.txtFiled.text};
    }
    
    [manage POST:kAddComment parameters:pardic
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
             [self requestGetComment];
             [_tableView reloadData];
             [_footerView.txtFiled setText:nil];
//             [self textFieldBackFrame];
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             // 请求失败的时候调用调用这个block
             NSLog(@"请求失败");
         }];
}

//点击return键恢复输入框原来的位置
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.view endEditing:YES];
    return YES;
}




#pragma mark - HeadView **********************************************

- (void)createNaviagtionView{
    _navigationView = [[HomeNavigationVIew alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
    [self.view addSubview:_navigationView];

    [_navigationView.TapGoodButton addTarget:self action:@selector(tapGood) forControlEvents:UIControlEventTouchUpInside];
    [_navigationView.shareBTN addTarget:self action:@selector(share) forControlEvents:UIControlEventTouchUpInside];
    
    [_navigationView.backButton addTarget:self action:@selector(backBefore) forControlEvents:(UIControlEventTouchUpInside)];
}

//点赞
- (void)tapGood{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *pardic = nil;
    if (_imageID) {
        pardic = @{@"id":_imageID,
                   @"type":@"photo"};
    }
    
    [manage GET:kZan parameters:pardic
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
             NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
             [self requestData];
             [_tableView reloadData];
             // 请求成功的时候调用这个block
             [MBProgressHUD show:@"感谢" icon:nil view:self.view];
             NSLog(@"数据请求点赞--%@", dic);
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             // 请求失败的时候调用调用这个block
             NSLog(@"请求失败");
         }];
}

// 创建分享选项卡
- (void)createShareView{
    _shareVC = [[ShareViewController alloc] init];
    [self.view addSubview:_shareVC.view];
    _shareVC.view.frame = CGRectMake(0,SCREEN_HEIGHT,SCREEN_WIDTH,SCREEN_HEIGHT);
}
//分享
- (void)share{
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionTransitionFlipFromBottom animations:^{
        _shareVC.view.frame = CGRectMake(0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
    } completion:^(BOOL finished) {
        
    }];
}

// 返回上一层
- (void)backBefore{
//    self.tabBarController.tabBar.hidden = NO;
    [self.navigationController popViewControllerAnimated:YES];

}


#pragma mark - barHidden**************************
- (BOOL)prefersStatusBarHidden{
    return YES;
}


#pragma mark - UITableViewDataSource**************************

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

//返回行数，也就是返回数组中所存储数据，也就是section的元素
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }
    else if (section == 1)
    {
        return 1;
    }
    else
    {
        return self.commentArray.count;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"Cell";
    if (indexPath.section == 0) {
        HomeDetialHeaderVIew *cell = [tableView dequeueReusableCellWithIdentifier:@"headerCell"];
        if (cell == nil) {
            cell = [[HomeDetialHeaderVIew alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"headerCell"];
        }
        HomeDetialModel *model = _dataSource[indexPath.row];
        cell.model = model;
        cell.backgroundColor = [UIColor whiteColor];
        cell.status = _status;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        // 长按手势button
        GHContextMenuView* overlay = [[GHContextMenuView alloc] init];
        overlay.dataSource = self;
        overlay.delegate = self;
        UILongPressGestureRecognizer* _longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:overlay action:@selector(longPressDetected:)];
        [cell.backgroundImageView setUserInteractionEnabled:YES];
        [cell.backgroundImageView addGestureRecognizer:_longPressRecognizer];
        
        return cell;
    }
    else if (indexPath.section == 1)
    {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"commentNumCell"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"commentNumCell"];
        }
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.5)];
        lineView.backgroundColor = kCustomColor(150, 150, 150, 0.1);
        [cell addSubview:lineView];
        
        cell.backgroundColor = kCustomColor(250, 250, 250, 1);
        cell.textLabel.text = @"评论";
        cell.textLabel.font = [UIFont systemFontOfSize:13];
        cell.textLabel.textColor = kCustomColor(150, 150, 150, 1);
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else
    {
        CommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil)
        {
            cell = [[CommentTableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:CellIdentifier];
        }
        //        cell.backgroundColor = [UIColor whiteColor];
        HomeCommentModel *model = _commentArray[indexPath.row];
        cell.backgroundColor = kCustomColor(250, 250, 250, 1);
        cell.model = model;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}

//设置单元格高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        HomeDetialModel *model = _dataSource[indexPath.row];
        CGFloat height = [HomeDetialHeaderVIew heightOfDetiallCell:model];
        return height;
    }
    else if (indexPath.section == 1)
    {
        return 40;
    }
    else
    {
        HomeCommentModel *model = _commentArray[indexPath.row];
        return [CommentTableViewCell heightOfCell:model];
    }
}

//选中单元格所产生事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

}



- (void)setImageID:(NSString *)imageID{
    _imageID = imageID;
}

- (void)setUserId:(NSString *)userId{
    _userId = userId;
}

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark --长按手势代理

- (NSInteger) numberOfMenuItems{
    return 3;
}

-(UIImage*) imageForItemAtIndex:(NSInteger)index{
    NSString* imageName = nil;
    switch (index) {
        case 0:
            imageName = @"AddFriend";
            break;
        case 1:
            imageName = @"TabGood";
            break;
        case 2:
            imageName = @"shareBigButton";
        default:
            break;
    }
    return [UIImage imageNamed:imageName];
}

- (void) didSelectItemAtIndex:(NSInteger)selectedIndex forMenuAtPoint:(CGPoint)point{
//    NSString* msg = nil;
    switch (selectedIndex) {
        case 0:
//            msg = @"加好友";
            break;
        case 1:
//            msg = @"d点赞";
            [self tapGood];
            break;
        case 2:
//            msg = @"分享";
            [self share];
            break;
        default:
            break;
    }
}



@end
